import 'dart:io';
import 'package:dio/dio.dart';

class NetworkUtil {
  static String baseUrl = 'https://www.wyhgl.cn:3344';

  // post请求
  static void post(String url, {Map<String, dynamic> params, Function successCallBack, Function failCallBack}) {
    _baseRequest(url, params: params, successCallBack: successCallBack, failCallBack: failCallBack);
  }

  // 请求
  static void _baseRequest(String url, {Map<String, dynamic> params, Function successCallBack, Function failCallBack}) async {
    String errorMsg = '';
    int statusCode;

    try {
      Dio dio = Dio();
      dio.options.baseUrl = baseUrl;
      dio.options.contentType = ContentType('application', 'x-www-form-urlencoded',charset: 'utf-8');
      dio.options.connectTimeout = 15000;
      dio.options.receiveTimeout = 15000;

      // https证书校验
      (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate  = (client) {
        client.badCertificateCallback=(X509Certificate cert, String host, int port){
          return true;
        };
      };
      print('请求url : $url' + '\n参数 : $params');

      // 发送请求
      Response response = await dio.post(url, data: params);
      statusCode = response.statusCode;

      if (successCallBack != null) {
        successCallBack(response);
      }
      //处理错误部分
      if (statusCode < 0) {
        errorMsg = "网络请求错误,状态码:" + statusCode.toString();
        _handError(failCallBack, errorMsg);
        return;
      }

    } catch(exception) {
      _handError(failCallBack, exception.toString());
    }
  }

  // 异常统一处理
  static void _handError(Function failCallback, String errorMsg) {
    if (failCallback != null) {
      failCallback(errorMsg);
    }
  }
}